package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import databeans.User;
import formbeans.ChangePasswordForm;
import model.Model;
import model.UserDAO;

public class ChangePasswordAction extends Action {
	private FormBeanFactory<ChangePasswordForm> formBeanFactory = FormBeanFactory.getInstance(ChangePasswordForm.class);
	private UserDAO userDAO;
	
	//instantiation.
	public ChangePasswordAction(Model model) {
		userDAO = model.getUserDAO();
	}
    //return Name.
	public String getName() {
		return "changepassword.do";
	}
    
    public String perform(HttpServletRequest request) {
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        HttpSession session = request.getSession(false);

        String button = request.getParameter("button");
        if(button==null) return "changepassword.jsp";
        
        if(button.equals("Back")){
        	String redirect_to = (String) session.getAttribute("redirectto");
        	return redirect_to;
        }
        
        ChangePasswordForm form;
		try {
			form = formBeanFactory.create(request);
			request.setAttribute("changepasswordform",form);
	    	
	    	if (!form.isPresent()) {
	    		return "homepage.jsp";
	    	}
			
			errors.addAll(form.checkChangePasswordFormErrors());
			if (errors.size() != 0) {
				return "changepassword.jsp";
			}
			User user_change = (User) session.getAttribute("userchange");
	        User user;
			try {
				user = userDAO.lookup(user_change.getUserid());
				if (user == null) {
					errors.add("The user does not exist!");
					return "homepage.jsp";
				} else if (!user.checkPassword(form.getOldpassword())) {
					errors.add("Incorrect password");
					return "changepassword.jsp";
				}
				user.setPassword(request.getParameter("newpassword"));
				//errors.add("Change Password successfully!");
				userDAO.updateUser(user);
				String redirect_to = (String) session.getAttribute("redirectto");
	        	return redirect_to;
			} catch (DAOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
		} catch (FormBeanException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
    }
}
